package com.cwz.datasource.dynamic.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.cwz.datasource.dynamic.config.DefaultDataSourceProperties;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @program: w-demo
 * @description: 数据源工具类
 * @author: Wen
 **/
public class DataSourceUtils {
	/**
	 * @Description: 初始化 druid 数据源
	 * @Author: Wen
	 * @param druidDataSource:
	 * @param defaultDataSourceProperties:
	 * @return: void
	 **/
	public static void setDruidDataSource(DruidDataSource druidDataSource, DefaultDataSourceProperties defaultDataSourceProperties) throws SQLException {
		druidDataSource.setUrl(defaultDataSourceProperties.getUrl());
		druidDataSource.setUsername(defaultDataSourceProperties.getUsername());
		druidDataSource.setPassword(defaultDataSourceProperties.getPassword());
		druidDataSource.setInitialSize(defaultDataSourceProperties.getInitialSize());
		druidDataSource.setMinIdle(defaultDataSourceProperties.getMinIdle());
		druidDataSource.setMaxActive(defaultDataSourceProperties.getMaxActive());
		druidDataSource.setMaxWait(defaultDataSourceProperties.getMaxWait());
		druidDataSource.setConnectTimeout(defaultDataSourceProperties.getConnectTimeout());
		druidDataSource.setSocketTimeout(defaultDataSourceProperties.getSocketTimeout());
		druidDataSource.setTimeBetweenEvictionRunsMillis(defaultDataSourceProperties.getTimeBetweenEvictionRunsMillis());
		druidDataSource.setMinEvictableIdleTimeMillis(defaultDataSourceProperties.getMinEvictableIdleTimeMillis());
		druidDataSource.setMaxEvictableIdleTimeMillis(defaultDataSourceProperties.getMaxEvictableIdleTimeMillis());
		druidDataSource.setValidationQuery(defaultDataSourceProperties.getValidationQuery());
		druidDataSource.setTestWhileIdle(defaultDataSourceProperties.isTestWhileIdle());
		druidDataSource.setTestOnBorrow(defaultDataSourceProperties.isTestOnBorrow());
		druidDataSource.setTestOnReturn(defaultDataSourceProperties.isTestOnReturn());
		druidDataSource.setPoolPreparedStatements(defaultDataSourceProperties.isPoolPreparedStatements());
		druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(defaultDataSourceProperties.getMaxPoolPreparedStatementPerConnectionSize());
		druidDataSource.setFilters(defaultDataSourceProperties.getFilters());
		Properties properties = new Properties();
		properties.put("druid.stat.mergeSql", true);
		properties.put("druid.stat.slowSqlMillis", 5000);
		druidDataSource.setConnectProperties(properties);
	}

	/**
	 * @Description: 查询完毕释放连接
	 * @Author: Wen
	 * @param conn:
	 * @param ps:
	 * @param rs:
	 * @return: void
	 **/
	public static void release(Connection conn, PreparedStatement ps, ResultSet rs) {
		try {
			if (rs != null) {
				rs.close();
			}
			if (ps != null) {
				ps.close();
			}
			if (conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
